{% extends "base.html" %}

{% block title %}用户管理 - 交易监控系统{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h2>用户管理</h2>
                    <a href="/admin/users/add" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 添加用户
                    </a>
                </div>
                <div class="card-body">
                    {% if error %}
                    <div class="alert alert-danger" role="alert">
                        {{ error }}
                    </div>
                    {% endif %}
                    
                    {% if success %}
                    <div class="alert alert-success" role="alert">
                        操作成功！
                    </div>
                    {% endif %}
                    
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>状态</th>
                                    <th>角色</th>
                                    <th>会话时长</th>
                                    <th>最后登录</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for user in users %}
                                <tr>
                                    <td>{{ user.id }}</td>
                                    <td>{{ user.username }}</td>
                                    <td>
                                        {% if user.is_active %}
                                        <span class="badge bg-success">启用</span>
                                        {% else %}
                                        <span class="badge bg-danger">禁用</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if user.user_type == 'super_admin' %}
                                        <span class="badge bg-danger">超级管理员</span>
                                        {% elif user.user_type == 'admin' %}
                                        <span class="badge bg-primary">管理员</span>
                                        {% elif user.user_type == 'operator' %}
                                        <span class="badge bg-info">操作员</span>
                                        {% elif user.user_type == 'viewer' %}
                                        <span class="badge bg-warning">只读用户</span>
                                        {% elif user.user_type == 'visitor' %}
                                        <span class="badge bg-secondary">参观用户</span>
                                        {% else %}
                                        <span class="badge bg-secondary">普通用户</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ user.session_duration }} 分钟</td>
                                    <td>{{ user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else '从未登录' }}</td>
                                    <td>{{ user.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</td>
                                    <td>
                                        <div class="d-flex gap-1 justify-content-center">
                                            {% if user.username != 'admin' %}
                                            <a href="/admin/users/edit/{{ user.id }}" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button type="button" class="btn btn-sm btn-outline-danger delete-user-btn" 
                                                    data-user-id="{{ user.id }}" data-username="{{ user.username }}">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            <a href="/admin/users/reset_password/{{ user.id }}" class="btn btn-sm btn-outline-warning">
                                                <i class="fas fa-key"></i>
                                            </a>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<!-- 重置密码模态框 -->
{% for user in users %}
    {% if user.username != 'admin' %}
    <div class="modal fade" id="resetPasswordModal{{ user.id }}" tabindex="-1" aria-labelledby="resetPasswordModalLabel{{ user.id }}" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title" id="resetPasswordModalLabel{{ user.id }}">
                        <i class="fas fa-key me-2"></i>重置密码
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="/admin/users/reset_password/{{ user.id }}">
                    <div class="modal-body">
                        <div class="text-center mb-4">
                            <i class="fas fa-user-lock fa-3x text-warning mb-3"></i>
                            <h5>为用户 <strong>{{ user.username }}</strong> 设置新密码</h5>
                        </div>
                        
                        <div class="mb-4">
                            <label for="new_password{{ user.id }}" class="form-label fw-bold">
                                <i class="fas fa-lock me-2"></i>新密码
                            </label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-key"></i></span>
                                <input type="password" class="form-control" id="new_password{{ user.id }}" name="new_password" required>
                                <button class="btn btn-outline-secondary toggle-password" type="button" data-target="new_password{{ user.id }}">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            <label for="confirm_password{{ user.id }}" class="form-label fw-bold">
                                <i class="fas fa-lock-open me-2"></i>确认新密码
                            </label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-key"></i></span>
                                <input type="password" class="form-control" id="confirm_password{{ user.id }}" name="confirm_password" required>
                                <button class="btn btn-outline-secondary toggle-password" type="button" data-target="confirm_password{{ user.id }}">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times me-1"></i>取消
                        </button>
                        <button type="submit" class="btn btn-warning">
                            <i class="fas fa-key me-1"></i>重置密码
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {% endif %}
{% endfor %}
{% endblock %}

{% block extra_css %}
<style>
    /* 草绿色风格的确认对话框 */
    .custom-confirm-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1050;
        overflow: hidden;
        outline: 0;
        align-items: center;
        justify-content: center;
    }
    
    .custom-confirm-modal.show {
        display: flex;
    }
    
    .custom-confirm-dialog {
        position: relative;
        width: auto;
        max-width: 500px;
        margin: 0.5rem;
        pointer-events: none;
    }
    
    .custom-confirm-content {
        position: relative;
        display: flex;
        flex-direction: column;
        width: 100%;
        pointer-events: auto;
        background-color: #fff;
        background-clip: padding-box;
        border: 1px solid rgba(0, 0, 0, 0.2);
        border-radius: 0.75rem;
        outline: 0;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
        animation: fadeIn 0.3s ease-in-out;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .custom-confirm-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 1rem 1.5rem;
        border-bottom: 1px solid #dee2e6;
        border-top-left-radius: calc(0.75rem - 1px);
        border-top-right-radius: calc(0.75rem - 1px);
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
    }
    
    .custom-confirm-title {
        margin-bottom: 0;
        line-height: 1.5;
        font-weight: 600;
        font-size: 1.25rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .custom-confirm-close {
        float: right;
        font-size: 1.5rem;
        font-weight: 700;
        line-height: 1;
        color: white;
        text-shadow: 0 1px 0 #fff;
        opacity: 1;
        background-color: transparent;
        border: none;
        cursor: pointer;
        transition: opacity 0.15s ease-in-out;
    }
    
    .custom-confirm-close:hover {
        opacity: 0.8;
    }
    
    .custom-confirm-body {
        position: relative;
        flex: 1 1 auto;
        padding: 1.5rem;
        text-align: center;
    }
    
    .custom-confirm-icon {
        font-size: 3rem;
        color: #28a745;
        margin-bottom: 1rem;
    }
    
    .custom-confirm-text {
        font-size: 1.1rem;
        color: #495057;
        margin-bottom: 0.5rem;
    }
    
    .custom-confirm-warning {
        font-size: 0.9rem;
        color: #dc3545;
        font-weight: 500;
        margin-top: 1rem;
    }
    
    .custom-confirm-footer {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1rem 1.5rem;
        border-top: 1px solid #dee2e6;
        border-bottom-right-radius: calc(0.75rem - 1px);
        border-bottom-left-radius: calc(0.75rem - 1px);
        gap: 0.75rem;
    }
    
    .custom-confirm-btn {
        display: inline-block;
        font-weight: 400;
        color: #fff;
        text-align: center;
        vertical-align: middle;
        user-select: none;
        background-color: transparent;
        border: 1px solid transparent;
        padding: 0.5rem 1rem;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: 0.375rem;
        transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        cursor: pointer;
    }
    
    .custom-confirm-btn-secondary {
        color: #495057;
        background-color: #e9ecef;
        border-color: #dee2e6;
    }
    
    .custom-confirm-btn-secondary:hover {
        color: #495057;
        background-color: #dae0e5;
        border-color: #d3d9df;
    }
    
    .custom-confirm-btn-danger {
        color: #fff;
        background-color: #dc3545;
        border-color: #dc3545;
    }
    
    .custom-confirm-btn-danger:hover {
        color: #fff;
        background-color: #c82333;
        border-color: #bd2130;
    }
    
    /* 成功消息动画 */
    .success-message {
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 0.5rem;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        z-index: 1060;
        opacity: 0;
        transform: translateY(-20px);
        transition: opacity 0.3s ease, transform 0.3s ease;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-weight: 500;
    }
    
    .success-message.show {
        opacity: 1;
        transform: translateY(0);
    }
</style>
{% endblock %}

{% block extra_js %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function() {
        // 密码显示/隐藏功能
        const toggleButtons = document.querySelectorAll('.toggle-password');
        
        toggleButtons.forEach(button => {
            button.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target');
                const passwordInput = document.getElementById(targetId);
                
                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    this.innerHTML = '<i class="fas fa-eye-slash"></i>';
                } else {
                    passwordInput.type = 'password';
                    this.innerHTML = '<i class="fas fa-eye"></i>';
                }
            });
        });
        
        // 初始化所有工具提示
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
        
        // 创建草绿色风格的自定义确认对话框HTML
        const confirmDialogHTML = `
            <div id="customConfirmModal" class="custom-confirm-modal">
                <div class="custom-confirm-dialog">
                    <div class="custom-confirm-content">
                        <div class="custom-confirm-header">
                            <h5 class="custom-confirm-title">
                                <i class="fas fa-exclamation-circle"></i>
                                确认删除
                            </h5>
                            <button type="button" class="custom-confirm-close" id="closeConfirmModal">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="custom-confirm-body">
                            <div class="custom-confirm-icon">
                                <i class="fas fa-user-slash"></i>
                            </div>
                            <p class="custom-confirm-text">确定要删除用户 "<strong id="confirmUserName"></strong>" 吗？</p>
                            <p class="custom-confirm-warning">
                                <i class="fas fa-exclamation-triangle"></i>
                                此操作将永久删除该用户账户，且不可撤销。
                            </p>
                        </div>
                        <div class="custom-confirm-footer">
                            <button type="button" class="custom-confirm-btn custom-confirm-btn-secondary" id="cancelDeleteBtn">
                                <i class="fas fa-times"></i> 取消
                            </button>
                            <button type="button" class="custom-confirm-btn custom-confirm-btn-danger" id="confirmDeleteBtn">
                                <i class="fas fa-trash-alt"></i> 确认删除
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 创建成功消息HTML
        const successMessageHTML = `
            <div id="successMessage" class="success-message">
                <i class="fas fa-check-circle"></i>
                <span>用户已成功删除！</span>
            </div>
        `;
        
        // 将对话框和成功消息添加到body
        $('body').append(confirmDialogHTML);
        $('body').append(successMessageHTML);
        
        // 存储当前要删除的用户ID
        let currentDeleteUserId = null;
        
        // 打开确认对话框
        $('.delete-user-btn').on('click', function() {
            const userId = $(this).data('user-id');
            const username = $(this).data('username');
            
            // 设置对话框内容
            $('#confirmUserName').text(username);
            currentDeleteUserId = userId;
            
            // 显示对话框
            $('#customConfirmModal').addClass('show');
            
            // 防止背景滚动
            $('body').css('overflow', 'hidden');
        });
        
        // 关闭确认对话框
        function closeConfirmModal() {
            $('#customConfirmModal').removeClass('show');
            $('body').css('overflow', 'auto');
            currentDeleteUserId = null;
        }
        
        // 点击关闭按钮
        $('#closeConfirmModal').on('click', closeConfirmModal);
        
        // 点击取消按钮
        $('#cancelDeleteBtn').on('click', closeConfirmModal);
        
        // 点击确认删除按钮
        $('#confirmDeleteBtn').on('click', function() {
            if (currentDeleteUserId) {
                // 发送AJAX请求删除用户
                $.ajax({
                    url: `/admin/users/delete/${currentDeleteUserId}`,
                    type: 'POST',
                    beforeSend: function(xhr) {
                        // 设置CSRF令牌
                        const csrfToken = $('meta[name="csrf-token"]').attr('content');
                        if (csrfToken) {
                            xhr.setRequestHeader('X-CSRF-Token', csrfToken);
                        }
                    },
                    success: function() {
                        // 关闭对话框
                        closeConfirmModal();
                        
                        // 显示成功消息
                        const $successMessage = $('#successMessage');
                        $successMessage.addClass('show');
                        
                        // 从表格中移除对应的行
                        $(`[data-user-id="${currentDeleteUserId}"]`).closest('tr').remove();
                        
                        // 3秒后隐藏成功消息
                        setTimeout(function() {
                            $successMessage.removeClass('show');
                        }, 3000);
                    },
                    error: function(xhr) {
                        // 关闭对话框
                        closeConfirmModal();
                        
                        // 显示错误消息
                        let errorMessage = '删除用户失败';
                        if (xhr.responseJSON && xhr.responseJSON.error) {
                            errorMessage = xhr.responseJSON.error;
                        }
                        
                        // 使用Bootstrap的alert显示错误消息
                        const errorAlert = `
                            <div class="alert alert-danger alert-dismissible fade show position-fixed top-20 right-20 z-1060" role="alert">
                                <i class="fas fa-exclamation-circle mr-2"></i>
                                ${errorMessage}
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        `;
                        
                        $('body').append(errorAlert);
                        
                        // 3秒后自动关闭错误消息
                        setTimeout(function() {
                            $('.alert-danger').alert('close');
                        }, 3000);
                    }
                });
            }
        });
        
        // 点击对话框外部关闭对话框
        $('#customConfirmModal').on('click', function(e) {
            if (e.target === this) {
                closeConfirmModal();
            }
        });
        
        // ESC键关闭对话框
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('#customConfirmModal').hasClass('show')) {
                closeConfirmModal();
            }
        });
    });
</script>
{% endblock %}